package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;

import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author:篍
 * @Date: 2025/08/20 15:54
 * @Description:
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MemberInterceptor.class);
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String token = request.getHeader("authorization");

        // 如果token为空，响应401，重新登录
        if (StrUtil.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            Claims claims = tokenService.parseToken(token);
            Object id = claims.get("id");
            if (Objects.isNull(id)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

            MemberThreadLocal.setMemberId(Long.parseLong(id.toString()));
        } catch (NumberFormatException e) {
            log.error("token解析异常:{}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MemberThreadLocal.remove();
    }
}
